package com.tjp.eight.utils;

import com.tjp.eight.WApplication;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/17.
 */

public class OkCacheIntercepter {

    public static Cache getCache() {
        //设置缓存路径
        File httpCacheDirectory = new File(WApplication.getInstance().getCacheDir(), "responses");
        //设置缓存 10M
        Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
        return cache;
    }

    public static Interceptor getInterceptor() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!ApplicationUtil.isNetWorkConnected(WApplication.getInstance())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                    //LogCat.i("no network");
                }
                Response response = chain.proceed(request);

                if (ApplicationUtil.isNetWorkConnected(WApplication.getInstance())) {
                    int maxAge = 0 * 60; // 有网络时 设置缓存超时时间0个小时
                    // Log.i("has network maxAge="+maxAge);
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    // LogCat.i("network error");
                    int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                    // LogCat.i("has maxStale="+maxStale);
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                    // LogCat.i("response build maxStale="+maxStale);
                }
                return response;
            }
        };
        return interceptor;
    }


}
